package com.ktjy.t382.ch01.controller;

import com.ktjy.t382.ch01.entity.SysUser;
import com.ktjy.t382.ch01.service.SysUserService;
import com.ktjy.t382.ch01.util.RandomStringGenerator;
import com.ktjy.t382.ch01.util.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    SysUserService sysUserService;

    @RequestMapping("/select")
    public SysUser select(@RequestBody SysUser sysUser) {
        SysUser user = sysUserService.select(sysUser);
        ;
        return user;
    }

    @RequestMapping("/login")
    public Map<String, Object> login(@RequestBody SysUser sysUser) {
        RedisUtil redisUtil = new RedisUtil();
        RandomStringGenerator generator = new RandomStringGenerator();
        String s = generator.generateRandomString(6);
        redisUtil.setKey("token", s);
        SysUser user = sysUserService.login(sysUser);
        Map<String, Object> map = new HashMap<>();
        if (user != null) {
            map.put("user", user);
            String token = redisUtil.getKey("token");
            map.put("token", token);
        } else {
            map.put("user", "登陆失败");
        }
        return map;
    }

    @RequestMapping("/balance")
    public BigDecimal getBalance(String cardno) {
        return sysUserService.getBalance(cardno);
    }

    @RequestMapping("/update")
    public Map<String, Object> update(@RequestBody SysUser account) {
        Map<String, Object> map = new HashMap<>();
        int password = sysUserService.update(account);
        if (password == 0) {
            map.put("code", 0);
            map.put("success", "修改失败");
        } else if (password > 0) {
            map.put("code", 1);
            map.put("success", "修改成功");
        }
        return map;
    }

    @RequestMapping("/transfer")
    public String transfer(String name1, String name2, BigDecimal amount) {
        return sysUserService.transfer(name1, name2, amount);
    }

    @RequestMapping("/password")
    public String password(String cardno) {
        return sysUserService.getPassword(cardno);
    }
}
